package com.xhblog.utils;

import io.jsonwebtoken.Jwt;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.log4j.Log4j2;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author pengyouhong
 * create 2022/5/18 17:44
 */

@Log4j2
public class JwtUtils {
    private static final String jwtToken = "loveYou3000times";


    /**
     * 获取token
     *
     * @param userId 用户id
     * @return 返回token
     * <p>
     * JwtBuilder jwtBuilder = Jwts.builder()
     * .signWith(SignatureAlgorithm.HS256, jwtToken)    签发算法，密钥为jwtToken
     * .setClaims(claims)                               body数据，要唯一，自行设置
     * .setIssuedAt(new Date())                         签发时间
     * .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 60 * 1000));   一天的有效时间
     * String token = jwtBuilder.compact();
     */
    public static String createToken(Long userId) {
        HashMap<String, Object> claims = new HashMap<>();

        claims.put("userId", userId);

        JwtBuilder jwtBuilder = Jwts.builder()
                .signWith(SignatureAlgorithm.HS256, jwtToken)
                .setClaims(claims)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 60 * 1000));
        String token = jwtBuilder.compact();

        return token;
    }


    /**
     * 验证token
     *
     * @param token token
     * @return 返回方法体
     */
    public static Map<String, Object> checkToken(String token) {
        try {
            Jwt parse = Jwts.parser().setSigningKey(jwtToken).parse(token);

            log.info("----------------token验证成功----------------");

            return (Map<String, Object>) parse.getBody();
        } catch (Exception exception) {
            exception.printStackTrace();
            log.error(exception.getMessage());
        }
        log.info("----------------token验证失败----------------");
        return null;
    }


    public static void main(String[] args) {
        String token = JwtUtils.createToken(1L);

        System.out.println(token);

        Map<String, Object> map = JwtUtils.checkToken("eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NTM3NTc1NzIsInVzZXJJZCI6MSwiaWF0IjoxNjUyODY4NTM5fQ._iLCq0FeMGIJ7P75EOBK11F5VSncZK8jxoO52ljIDnk");

        System.out.println(map);
    }
}
